<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="通过前面几节的讲解，我们已经基本了解了 class 文件的结构,每个字段代表什么含义,占多少字节,那么明确了 Class 文件的规则,接下来就可以读取 class 文件了，本节的代码均在项目的 classfile 包下。   Class 文件的结构这里再次贴出 class 文件的结构描述： 123456789101112131415161718ClassFile &amp;#123;  u4 magic">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(7)-读取class文件">
<meta property="og:url" content="https://zachaxy.github.io/2017/05/10/手写JVM系列-7-读取class文件/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="通过前面几节的讲解，我们已经基本了解了 class 文件的结构,每个字段代表什么含义,占多少字节,那么明确了 Class 文件的规则,接下来就可以读取 class 文件了，本节的代码均在项目的 classfile 包下。   Class 文件的结构这里再次贴出 class 文件的结构描述： 123456789101112131415161718ClassFile &amp;#123;  u4 magic">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.305Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(7)-读取class文件">
<meta name="twitter:description" content="通过前面几节的讲解，我们已经基本了解了 class 文件的结构,每个字段代表什么含义,占多少字节,那么明确了 Class 文件的规则,接下来就可以读取 class 文件了，本节的代码均在项目的 classfile 包下。   Class 文件的结构这里再次贴出 class 文件的结构描述： 123456789101112131415161718ClassFile &amp;#123;  u4 magic">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/05/10/手写JVM系列-7-读取class文件/">





  <title>手写JVM系列(7)-读取class文件 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/05/10/手写JVM系列-7-读取class文件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(7)-读取class文件</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-10T16:21:24+08:00">
                2017-05-10
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,683
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <blockquote>
<p>通过前面几节的讲解，我们已经基本了解了 class 文件的结构,每个字段代表什么含义,占多少字节,那么明确了 Class 文件的规则,接下来就可以读取 class 文件了，本节的代码均在<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目</a>的 classfile 包下。</p>
</blockquote>
<hr>
<h1 id="Class-文件的结构"><a href="#Class-文件的结构" class="headerlink" title="Class 文件的结构"></a>Class 文件的结构</h1><p>这里再次贴出 class 文件的结构描述：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">ClassFile &#123;</span><br><span class="line">  u4 magic;	<span class="comment">//魔数</span></span><br><span class="line">  u2 minor_version;	<span class="comment">//次版本号</span></span><br><span class="line">  u2 major_version;	<span class="comment">//主版本号</span></span><br><span class="line">  u2 constant_pool_count;	<span class="comment">//常量池大小</span></span><br><span class="line">  cp_info constant_pool[constant_pool_count-<span class="number">1</span>]; <span class="comment">//常量池</span></span><br><span class="line">  u2 access_flags;	<span class="comment">//类访问标志,表明 class 文件定义的是类还是接口，访问级别是 public 还是 private，等</span></span><br><span class="line">  u2 this_class;	<span class="comment">//</span></span><br><span class="line">  u2 super_class;	<span class="comment">//</span></span><br><span class="line">  u2 interfaces_count;	<span class="comment">//本类实现的接口数量</span></span><br><span class="line">  u2 interfaces[interfaces_count];	<span class="comment">//实现的接口,存放在数组中</span></span><br><span class="line">  u2 fields_count;		<span class="comment">//本来中含有字段数</span></span><br><span class="line">  field_info fields[fields_count];	<span class="comment">//数组中存放这各个字段</span></span><br><span class="line">  u2 methods_count;		<span class="comment">//本类中含有的方法数</span></span><br><span class="line">  method_info methods[methods_count];	<span class="comment">//数组中存放着各个方法</span></span><br><span class="line">  u2 attributes_count;			<span class="comment">//本类中含有的属性数量;</span></span><br><span class="line">  attribute_info attributes[attributes_count];	<span class="comment">//数组中存放着各个属性</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="ClassFile-类"><a href="#ClassFile-类" class="headerlink" title="ClassFile 类"></a>ClassFile 类</h1><p>根据上面的 class 结构类型，我们自己定义的类 ClassFile 也呼之欲出,每个字段和上述 class 结构几乎是一样的。类中的一个成员变量定义如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassFile</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">int</span> minorVersion;</span><br><span class="line">    <span class="keyword">int</span> majorVersion;</span><br><span class="line">    ConstantPool constantPool;</span><br><span class="line">    <span class="keyword">int</span> accessFlags;</span><br><span class="line">    <span class="keyword">int</span> thisClass;</span><br><span class="line">    <span class="keyword">int</span> superClass;</span><br><span class="line">    <span class="keyword">int</span>[] interfaces;</span><br><span class="line">    MemberInfo[] fields;</span><br><span class="line">    MemberInfo[] methods;</span><br><span class="line">    AttributeInfo[] attributes;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ClassFile</span><span class="params">(<span class="keyword">byte</span>[] classData)</span> </span>&#123;</span><br><span class="line">        ClassReader reader = <span class="keyword">new</span> ClassReader(classData);</span><br><span class="line">        read(reader);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">read</span><span class="params">(ClassReader reader)</span> </span>&#123;</span><br><span class="line">        readAndCheckMagic(reader);  <span class="comment">//验证魔数</span></span><br><span class="line">        readAndCheckVersion(reader);	<span class="comment">//校验版本</span></span><br><span class="line">        constantPool = <span class="keyword">new</span> ConstantPool(reader);	<span class="comment">//创建常量池</span></span><br><span class="line">        accessFlags = reader.readUint16();		<span class="comment">//获取类访问标志</span></span><br><span class="line">        thisClass = reader.readUint16();		<span class="comment">//</span></span><br><span class="line">        superClass = reader.readUint16();		<span class="comment">//</span></span><br><span class="line">        interfaces = reader.readUint16s();		<span class="comment">//</span></span><br><span class="line">        fields = MemberInfo.readMembers(reader, constantPool);	<span class="comment">//</span></span><br><span class="line">        methods = MemberInfo.readMembers(reader, constantPool);	<span class="comment">//</span></span><br><span class="line">        attributes = AttributeInfo.readAttributes(reader, constantPool);	<span class="comment">//</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以很清晰的看到,我们定义的 ClassFile 文件,可以看到成员变量和 JVM 中关于 class 文件的描述是一致的,只不过这里为了方便编码,统一用 int 类型来保存 u1,u2 和 u4 类型的值.</p>
<h1 id="Class-文件字节码读取辅助类"><a href="#Class-文件字节码读取辅助类" class="headerlink" title="Class 文件字节码读取辅助类"></a>Class 文件字节码读取辅助类</h1><p>接下来要解决的问题是每个字段所占的字节数不同,所以这里我们需要若干方法根据字节数读取相应的字节,所有有创建了一个<code>ClassReader</code>类,并令该类持有 class 字节码，并且在该类中保存一个 index，表明现在是从哪个字节开始读.并且提供了读取 1 字节,2 字节,4 字节,8 字节等方法,来满足<code>ClassFile</code>类中个字段对应的字节数的需求。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassReader</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">byte</span>[] data;</span><br><span class="line">    <span class="keyword">int</span> index = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ClassReader</span><span class="params">(<span class="keyword">byte</span>[] data)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.data = data;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// u1</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">byte</span> <span class="title">readUint8</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span> res = data[index++];</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// u2 这里是读取一个无符号的 16 位整,java 中没有,只能用 int 来代替吧;</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">readUint16</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">2</span>];</span><br><span class="line">        res[<span class="number">0</span>] = data[index++];</span><br><span class="line">        res[<span class="number">1</span>] = data[index++];</span><br><span class="line">        <span class="keyword">return</span> ByteUtils.bytesToU16(res);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// u4</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readUint32() &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">4</span>];</span><br><span class="line">        res[<span class="number">0</span>] = data[index++];</span><br><span class="line">        res[<span class="number">1</span>] = data[index++];</span><br><span class="line">        res[<span class="number">2</span>] = data[index++];</span><br><span class="line">        res[<span class="number">3</span>] = data[index++];</span><br><span class="line"><span class="comment">//        return ByteUtils.bytesToU32(res);  //如果需要转换的话,自行调用 ByteUtils 中的方法;</span></span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readUint64() &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">8</span>];</span><br><span class="line">        res[<span class="number">0</span>] = data[index++];</span><br><span class="line">        res[<span class="number">1</span>] = data[index++];</span><br><span class="line">        res[<span class="number">2</span>] = data[index++];</span><br><span class="line">        res[<span class="number">3</span>] = data[index++];</span><br><span class="line">        res[<span class="number">4</span>] = data[index++];</span><br><span class="line">        res[<span class="number">5</span>] = data[index++];</span><br><span class="line">        res[<span class="number">6</span>] = data[index++];</span><br><span class="line">        res[<span class="number">7</span>] = data[index++];</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span>[] readUint16s() &#123;</span><br><span class="line">        <span class="keyword">int</span> n = readUint16();</span><br><span class="line">        <span class="keyword">int</span>[] data = <span class="keyword">new</span> <span class="keyword">int</span>[n];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            data[i] = readUint16();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> data;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] readBytes(<span class="keyword">int</span> n) &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] res = <span class="keyword">new</span> <span class="keyword">byte</span>[n];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            res[i] = data[index++];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在有了 ClassReader 这样的工具类之后,我们就可以在 ClassFile 中根据不同的字段，使用不同的 ClassReader#readXXX() 方法,来初始化成员变量,这里定义了一个 ClassFile#read() 方法来完成 ClassFile 类的初始化成员变量的任务。</p>
<h1 id="简单字段的实现"><a href="#简单字段的实现" class="headerlink" title="简单字段的实现"></a>简单字段的实现</h1><p>对于 ClassFile 的字段，除了常量和属性两个区域，其它的字段都可以很容易根据其占用的字节长度读出来，这对于编码来说并没有什么难度。在 ClassFile#read 方法中实现了所有字段的读取。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">read</span><span class="params">(ClassReader reader)</span> </span>&#123;</span><br><span class="line">    readAndCheckMagic(reader);</span><br><span class="line">    readAndCheckVersion(reader);</span><br><span class="line">    constantPool = <span class="keyword">new</span> ConstantPool(reader);</span><br><span class="line">    accessFlags = reader.readUint16();</span><br><span class="line">    thisClass = reader.readUint16();</span><br><span class="line">    superClass = reader.readUint16();</span><br><span class="line">    interfaces = reader.readUint16s();</span><br><span class="line">    fields = MemberInfo.readMembers(reader, constantPool);</span><br><span class="line">    methods = MemberInfo.readMembers(reader, constantPool);</span><br><span class="line">    attributes = AttributeInfo.readAttributes(reader, constantPool);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是对于常量和属性，因为其各自又包含了许多种类，所以需要针对不同的常量，不同的属性进行不同的读取。接下来分别介绍如何实现常量和属性的读取。</p>
<h1 id="常量的实现"><a href="#常量的实现" class="headerlink" title="常量的实现"></a>常量的实现</h1><p>这里需要定义一个常量的抽象类 ConstantInfo，表示一个常量 item，具体的常量由其子类实现，这里对外提供一个统一的接口来根据不同的 tag，创建不同的具体常量实现类，以完成常量池的初始化。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ConstantInfo <span class="title">create</span><span class="params">(<span class="keyword">int</span> tag, ConstantPool constantPool)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (tag) &#123;</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Integer:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantIntegerInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Float:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantFloatInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Long:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantLongInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Double:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantDoubleInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Utf8:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantUtf8Info();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_String:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantStringInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Class:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantClassInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Fieldref:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMemberRefInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_Methodref:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMemberRefInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_InterfaceMethodref:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMemberRefInfo(constantPool);</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_NameAndType:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantNameAndTypeInfo();</span><br><span class="line">        <span class="comment">// <span class="doctag">TODO:</span> 2017/5/3 0003 下面三个类还未编码; </span></span><br><span class="line">        <span class="keyword">case</span> CONSTANT_MethodType:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMethodTypeInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_MethodHandle:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantMethodHandleInfo();</span><br><span class="line">        <span class="keyword">case</span> CONSTANT_InvokeDynamic:</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantInvokeDynamicInfo();</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"java.lang.ClassFormatError: constant pool tag!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>并且提供一个抽象方法，供子类实现，因为每种常量所占的字节数并不相同。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">readInfo</span><span class="params">(ClassReader reader)</span></span></span><br></pre></td></tr></table></figure>

<p>而对于各自具体的常量，需要根据各自常量的结构来读取，其结构已经在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-5-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B8%B8%E9%87%8F%E6%B1%A0/">手写 JVM 系列(5)-分析 class 文件-常量池</a>中进行了详细的介绍。具体实现请参照<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目源码</a></p>
<h1 id="常量池的实现"><a href="#常量池的实现" class="headerlink" title="常量池的实现"></a>常量池的实现</h1><p>有了上面各个常量的具体实现，那么接下来我们就可以构建常量池了。常量池其实就是本 class 文件中所有常量的集合。</p>
<p>因为常量池是根据索引来访问的，因此我们也很自然的想到用数组来表示常量池，数组类型是上面定义的常量类型，注意索引从 1 开始，0 是无效索引。常量池的初始化时在构造方法中，通过 ConstantInfo 提供的 readConstantInfo 静态方法，读取一字节 tag，根据 tag 创建不同的常量实现类，并添加到常量池数组中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RuntimeConstantPool</span> </span>&#123;</span><br><span class="line">    ConstantInfo[] infos;  <span class="comment">//保存类文件常量池中的所有常量,常量分为多种类型,基本类型都有对应的常量,以及字符串等;(简言之,这就是常量池的抽象)</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> constantPoolCount; <span class="comment">//class 文件中常量池中的常量数量</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ConstantPool</span><span class="params">(ClassReader reader)</span> </span>&#123;</span><br><span class="line">        <span class="comment">/*读出常量池的大小;接下来根据这个大小,生成常量信息数组;</span></span><br><span class="line"><span class="comment">        注意:</span></span><br><span class="line"><span class="comment">        1. 表头给出的常量池大小比实际大 1,所以这样的话,虽然可能生成了这么大的,但是 0 不使用,直接从 1 开始;</span></span><br><span class="line"><span class="comment">        2. 有效的常量池索引是 1~n–1。0 是无效索引，表示不指向任何常量</span></span><br><span class="line"><span class="comment">        3. CONSTANT_Long_info 和 CONSTANT_Double_info 各占两个位置。</span></span><br><span class="line"><span class="comment">           也就是说，如果常量池中存在这两种常量，实际的常量数量比 n–1 还要少，而且 1~n–1 的某些数也会变成无效索引。</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">        constantPoolCount = reader.readUint16();</span><br><span class="line">        infos = <span class="keyword">new</span> ConstantInfo[constantPoolCount];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; constantPoolCount; i++) &#123;</span><br><span class="line">            infos[i] = ConstantInfo.readConstantInfo(reader, <span class="keyword">this</span>);</span><br><span class="line">            <span class="keyword">if</span> ((infos[i] <span class="keyword">instanceof</span> ConstantLongInfo) || (infos[i] <span class="keyword">instanceof</span> ConstantDoubleInfo)) &#123;</span><br><span class="line">                i++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">  ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="属性的实现"><a href="#属性的实现" class="headerlink" title="属性的实现"></a>属性的实现</h1><p>对于属性的编码，和常量池的编码思路是相似的，其实这里称为“属性池”更为贴切。因为他是各种属性的集合。而 class 文件本身，方法表集合和字段表集合中均持有属性表。</p>
<p>同样，提供一个抽象类来表示一个属性，其定义如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AttributeInfo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">readInfo</span><span class="params">(ClassReader reader)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//读取单个属性</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> AttributeInfo <span class="title">readAttribute</span><span class="params">(ClassReader reader, ConstantPool constantPool)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> attrNameIndex = reader.readUint16();</span><br><span class="line">        String attrName = constantPool.getUtf8(attrNameIndex);</span><br><span class="line">        <span class="keyword">int</span> attrLen = ByteUtils.byteToInt32(reader.readUint32());</span><br><span class="line">        AttributeInfo attrInfo = create(attrName, attrLen, constantPool);</span><br><span class="line">        attrInfo.readInfo(reader);</span><br><span class="line">        <span class="keyword">return</span> attrInfo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//读取属性表;这个和 ConstantPool 中的方法类似,一般都是一下全部读取出来,不会只读一个</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> AttributeInfo[] readAttributes(ClassReader reader, ConstantPool constantPool) &#123;</span><br><span class="line">        <span class="keyword">int</span> attributesCount = reader.readUint16();</span><br><span class="line">        AttributeInfo[] attributes = <span class="keyword">new</span> AttributeInfo[attributesCount];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; attributesCount; i++) &#123;</span><br><span class="line">            attributes[i] = readAttribute(reader, constantPool);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> attributes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//Java 虚拟机规范预定义了 23 种属性，先解析其中的 8 种</span></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    23 种预定义属性可以分为三组。</span></span><br><span class="line"><span class="comment">    第一组属性是实现 Java 虚拟机所必需的，共有 5 种；</span></span><br><span class="line"><span class="comment">    第二组属性是 Java 类库所必需的，共有 12 种；</span></span><br><span class="line"><span class="comment">    第三组属性主要提供给工具使用，共有 6 种。第三组属性是可选的，也就是说可以不出现在 class 文件中。</span></span><br><span class="line"><span class="comment">    (如果 class 文件中存在第三组属性，Java 虚拟机实现或者 Java 类库也是可以利用它们的，比如使用 LineNumberTable 属性在异常堆栈中显示行号。)</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> AttributeInfo <span class="title">create</span><span class="params">(String attrName, <span class="keyword">int</span> attrLen, ConstantPool constantPool)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (attrName.equals(<span class="string">"Code"</span>)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> CodeAttribute(constantPool);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"ConstantValue"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ConstantValueAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"Deprecated"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> DeprecatedAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"Exceptions"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> ExceptionsAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"LineNumberTable"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> LineNumberTableAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"LocalVariableTable"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> LocalVariableTableAttribute();</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"SourceFile"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> SourceFileAttribute(constantPool);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (attrName.equals(<span class="string">"Synthetic"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> SyntheticAttribute();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> UnparsedAttribute(attrName, attrLen);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其内部定义了抽象方法 readInfo，供各具体的属性类去读取相应的数据。而对外，提供了一个 readAttributes 的方法，来返回当前 方法表集合或者字段表集合中的的属性集合。与常量池不同的是：常量是根据不同的 tag（代表一个整数）来区分不同的常量，而属性是根据不同的 name（字符串）来区分不同的属性，所以创建属性的方法 AttributeInfo#create 方法。</p>
<p>而对于各自具体的属性，需要根据各自属性的结构来读取，其结构已经在<a href="https://zachaxy.github.io/2017/05/09/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-6-%E5%88%86%E6%9E%90class%E6%96%87%E4%BB%B6-%E5%B1%9E%E6%80%A7%E8%A1%A8/">手写 JVM 系列(6)-分析 class 文件-属性表</a>中进行了详细的介绍。具体实现请参照<a href="https://github.com/zachaxy/JVM" target="_blank" rel="noopener">项目源码</a></p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/05/10/手写JVM系列-7-读取class文件/" title="手写JVM系列(7)-读取class文件">https://zachaxy.github.io/2017/05/10/手写JVM系列-7-读取class文件/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/09/手写JVM系列-6-分析class文件-属性表/" rel="next" title="手写JVM系列(6)-分析class文件-属性表">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(6)-分析class文件-属性表
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/05/11/对LayoutParams的理解/" rel="prev" title="对LayoutParams的理解">
                对LayoutParams的理解 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Class-文件的结构"><span class="nav-number">1.</span> <span class="nav-text">Class 文件的结构</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ClassFile-类"><span class="nav-number">2.</span> <span class="nav-text">ClassFile 类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Class-文件字节码读取辅助类"><span class="nav-number">3.</span> <span class="nav-text">Class 文件字节码读取辅助类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#简单字段的实现"><span class="nav-number">4.</span> <span class="nav-text">简单字段的实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常量的实现"><span class="nav-number">5.</span> <span class="nav-text">常量的实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常量池的实现"><span class="nav-number">6.</span> <span class="nav-text">常量池的实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#属性的实现"><span class="nav-number">7.</span> <span class="nav-text">属性的实现</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
